import React, { useState, useRef } from "react";
import MathJax from 'react-mathjax2'
import ExpressionDefinitions from "./expressions";
import "./App.css";

const Context = MathJax.Context;
const Node = MathJax.Node;

const App = () => {
  const [expression, setExpression] = useState("");
  const textareaRef = useRef();

  const insertTextAtCursor = (text) => {
    const { selectionStart, selectionEnd } = textareaRef.current;
    const textBefore = textareaRef.current.value.substring(0, selectionStart);
    const textAfter = textareaRef.current.value.substring(selectionEnd);
    let full_text = textBefore + text + textAfter;
    textareaRef.current.value = full_text
    textareaRef.current.selectionEnd = selectionStart + text.length;
    textareaRef.current.selectionStart = full_text;
    setExpression(full_text);
  };

  const handleClick = (e) => {
    const mathType = e.currentTarget.dataset.key;
    let v = ExpressionDefinitions[mathType];
    insertTextAtCursor(v);
  };

  return (
    <div className="latex-tool-container">
      <div className="formula-grid">
        {Object.keys(ExpressionDefinitions).map(key => (
          <button
            key={key}
            data-key={key}
            onClick={handleClick}
            className="formula-btn"
            title={ExpressionDefinitions[key]}
          >
            <Context>
              <Node inline>{ExpressionDefinitions[key]}</Node>
            </Context>
          </button>
        ))}
      </div>
      
      <textarea 
        className="latex-input" 
        ref={textareaRef} 
        onChange={(e) => setExpression(e.target.value)} 
        placeholder="输入或点击按钮插入 LaTeX 公式..." 
        value={expression} 
      />
      
      <div className="preview-wrapper">
        <div className="preview-label">预览</div>
        <div id="preview" className="preview-content">
          <Context>
            <Node>{expression || 'f(x) = x^2'}</Node>
          </Context>
        </div>
      </div>
    </div>
  );
};

export default App;
